package com.li.arithmetic;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.cookie.CookiePolicy;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

/**  
 * 类说明   
 *  
 * @author ****  
 * @date 2018年3月20日  新建  
 */
public class MyHttpLogin {
	public static void main(String[] args) throws HttpException, IOException, InterruptedException {
		// 登陆 Url
		String loginUrl = "https://passport.baidu.com/v2/api/?login";
		String yzmUrl = "https://passport.baidu.com/cgi-bin/genimage?jxGfa07c18c1d71c128026815354301367f30c0430787047e8d";
		HttpClient httpClient = new HttpClient();
		GetMethod getMethod = new GetMethod(yzmUrl);
		httpClient.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
		int statusCode=httpClient.executeMethod(getMethod);

		// 获得登陆后的 Cookie
		Cookie[] cookies = httpClient.getState().getCookies();
		StringBuffer tmpcookies = new StringBuffer();
		for (Cookie c : cookies) {
			tmpcookies.append(c.toString() + ";");
			System.out.println("cookies = "+c.toString());
		}
		InputStream is = getMethod.getResponseBodyAsStream();
		FileOutputStream fos = new FileOutputStream("login.jpg");
		byte[] bs = new byte[1024];
		int len = 0;
		while ((len = is.read(bs)) != -1) {
            fos.write(bs, 0, len);
        }
		fos.flush();
		is.close();
		fos.close();
		File imageFile = new File("login.jpg");  
		Tesseract instance = new Tesseract();

		//将验证码图片的内容识别为字符串 
		String result = null;
		try {
			result = instance.doOCR(imageFile).trim();
		} catch (TesseractException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if(statusCode==200){//重定向到新的URL
			System.out.println("验证码获取成功");
			PostMethod postMethod = new PostMethod(loginUrl);

			// 设置登陆时要求的信息，用户名和密码
			NameValuePair[] data = { new NameValuePair("loginName", "lzadmin"), new NameValuePair("password", "654321") ,new NameValuePair("verifyCode",result)};
			postMethod.setRequestBody(data);
			// 每次访问需授权的网址时需带上前面的 cookie 作为通行证
			postMethod.setRequestHeader("cookie", tmpcookies.toString());
			int statusCode2 = httpClient.executeMethod(postMethod);
			if(statusCode2 == 200){
				System.out.println("登录成功");
			}
		}
	}
}
